package com.lanzhou.yuanfen.security.session;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * @ClassName: {@link SessionListener}
 * @Description: servlet 包提供的Session属性监听器, 当session添加删除替换的时候监听
 * @author: Lanzhou
 * @date: 2020/5/28 19:21
 * @QQ: 1627518680
 * @Copyright:2020 All rights reserved.
 */
@Slf4j
@WebListener
public class SessionListener implements HttpSessionAttributeListener {

    /**
     * 内部Session认证属性
     * 详情见: WebSessionServerSecurityContextRepository.setSpringSecurityContextAttrName 注释
     * HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY 注释
     */
    private final static String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT";

    @Resource
    private GlobalSessionContext globalSessionContext;

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        if (SPRING_SECURITY_CONTEXT.equals(se.getName())) {
            globalSessionContext.add(se.getSession());
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {
        if (SPRING_SECURITY_CONTEXT.equals(se.getName())) {
            globalSessionContext.delete(se.getSession());
        }
    }

    /**
     * 监听属性变化HttpSessionRequestCache
     *
     * @param se
     */
    @Override
    public void attributeReplaced(HttpSessionBindingEvent se) {
        String name = se.getName();
        Object value = se.getValue();
        HttpSession session = se.getSession();
        System.out.println("============================================================");
        System.out.println(name);
        System.out.println(JSON.toJSONString(value));
        System.out.println(JSON.toJSONString(session));
        log.info("当前session的属性已经发生了改变..");
    }
}